<?php
namespace Home\Model;
use \Think\Model;
class RecommendModel extends Model
{
	//字段映射
	protected $_map = array(
		'recommendId' => 'recommend_id',
		'recommendedId' => 'recommended_id',
		'createTime' => 'create_time',
		'updateTime' => 'update_time',
		'expireTime' => 'expire_time',
	);
	
	//自动验证
	protected $_validate = array(
		array('recommended_id', '/^[1-9]\d*$/', '被推荐人id错误', 2, 'regex', 3),
		array('code', '/^\w{6,12}$/', '推荐码错误', 1, 'regex', 1),
		array('code', '', '推荐码重复，请重新生成', 1, 'unique',1),
		array('code', 'checkCode', '推荐码已过期', 2, 'callback', 2),
		array('expire_time', '/^\d{10,}$/', '推荐码有效期错误', 1, 'regex', 1),
	);
	
	//自动完成
	protected $_auto = array(
		array('create_time', NOW_TIME, 1, 'string'),
		array('update_time', NOW_TIME, 3, 'string'),
		array('status', 0, 1, 'string')
	);
	
	/**
	 * 添加推荐码记录
	 * @author 刘新
	 */
	public function addRecommend($data)
	{
		if(!$this->create($data)) return array('error' => 1,'info' => $this->getError());
		$res = $this->add();
		
		if(!$res) return array('error' => 1,'info' => '推荐码获取失败');
		return array('error' => 0,'info' => $data['code']);
	}
	
	/**
	 * 更新推荐码记录
	 * @author 刘新
	 */
	public function editRecommend($data)
	{
		if(!$this->create($data,2)) return array('error' => 1,'info' => $this->getError());
		
		//更新条件
		$where = array();
		if($data['code']) $where['code'] = $data['code'];
		if($data['id']) $where['id'] = $data['id'];
		
		//更新
		$res = $this->where($where)->save();
	
		if(!$res) return array('error' => 1,'info' => '推荐码更新失败');
		return array('error' => 0,'info' => '更新成功');
	}
	
	/**
	 * 验证推荐码有效期
	 * @param string $code
	 * @author 刘新
	 */
	protected function checkCode($code)
	{
		$res = M('Recommend')->where(array('code' => $code, 'status' => 0))->order('expire_time desc')->field('code,expire_time')->find();
		if(!$res) return false;
		if($code == $res['code'] && $res['expire_time'] > time()) return true;
		return false;
	}
}